/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.config;

import static com.huawei.housekeeper.common.constant.ConfigConstant.TENANT_MAP_NAME;

import com.huawei.housekeeper.common.entity.SetPropertyDto;
import com.huawei.housekeeper.common.utils.K8sUtil;
import com.huawei.housekeeper.dao.mapper.PropertyMapper;

import io.kubernetes.client.openapi.models.V1ConfigMap;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

import javax.annotation.PostConstruct;

/**
 * 启动初始化同步tenantMap信息
 *
 * @author y84241604
 * @since 2022-07-04
 */
@Component
@Slf4j
public class TenantMapInitConfig {

    @Autowired
    K8sUtil k8sUtil;

    @Autowired
    PropertyMapper propertyMapper;

    @Value("${k8s.configName}")
    private String configName;

    @Value("${spring.cloud.kubernetes.config.namespace}")
    private String namespace;

    /**
     * 从数据库获取租户信息同步至configMap中的tenantMap
     */
    @PostConstruct
    public void initTenantInformationToConfigMap() {
        log.info("Read the tenant information from the database and synchronize it to tenantMap in configMap");
        List<SetPropertyDto> list = propertyMapper.getProperties();
        if (!CollectionUtils.isEmpty(list)) {
            V1ConfigMap configMap = k8sUtil.getConfigMap(namespace, configName);
            list.stream().forEach(var1 -> {
                configMap.putDataItem(TENANT_MAP_NAME + "." + var1.getKey(), var1.getValue());
            });
            log.info("configMap Data: {}", configMap.getData());
            k8sUtil.updateConfigMap(configMap, namespace, configName);
        }
    }
}
